package com.bw.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bw.dao.OrderConfigMapper;
import com.bw.dao.OrderItemMapper;
import com.bw.dao.OrderLogMapper;
import com.bw.pojo.goods.Commodityrecord;
import com.bw.pojo.goods.Goods;
import com.bw.pojo.goods.Spu;
import com.bw.pojo.order.*;
import com.bw.service.goods.SkuService;
import com.bw.service.order.CartService;
import com.bw.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.bw.dao.OrderMapper;
import com.bw.entity.PageResult;
import com.bw.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class)
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private CartService cartService;

    @Reference
    private SkuService skuService;



    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    public List<Order> findAllList(String []ids){
        ArrayList<Order> orders = new ArrayList<>();
        for (String id : ids) {
            Order byId = findById(id);
            orders.add(byId);
        }
        return orders;
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     * @return
     */
    public Map<String,Object> add(Order order){
        //获取购物车（刷新单价）
        List<Map<String,Object>> orderItemList = cartService.findNewOrderItemList(order.getUsername());
        //获取选中的购物车
        List<OrderItem> orderItems = orderItemList.stream().filter(cart ->(boolean) cart.get("checked")).map(cart ->(OrderItem) cart.get("item")).collect(Collectors.toList());
        //扣减库存
        if (!skuService.deductionStock(orderItems)){
            throw new RuntimeException("库存扣减失败");
        }
        //保存订单主表
        order.setId(idWorker.nextId()+"");
        //合计数计算
        IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
        IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);
        int totalNum= numStream.sum();//总数量
        int totalMoney= moneyStream.sum();//订单总金额
        int preMoney = cartService.preferential(order.getUsername());//计算优惠金额
        order.setTotalNum(totalNum);//总数量
        order.setTotalMoney(totalMoney);//总金额
        order.setPreMoney(preMoney);//优惠金额
        order.setPayMoney(totalMoney-preMoney);//支付金额=总金额-优惠金额
        order.setCreateTime(new Date());//订单创建日期
        order.setOrderStatus("0");//订单状态
        order.setPayStatus("0");//支付状态：未支付
        order.setConsignStatus("0");//发货状态：未发货
        order.setIsDelete("0");//是否删除：否
        orderMapper.insert(order);

        double proportion = (double) order.getPayMoney()/totalMoney;
        //保存订单明细
        for (OrderItem orderItem:orderItems){
            orderItem.setOrderId(order.getId());//订单主表ID
            orderItem.setId(idWorker.nextId()+"");
            orderItem.setPayMoney((int)(orderItem.getMoney()*proportion));//支付金额
            orderItemMapper.insert(orderItem);
        }
        //清除选中的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String,Object> map = new HashMap();
        map.put("ordersn",order.getId());
        map.put("money",order.getPayMoney());
        return map;
    }
//    public void add(Order order) {
//        orderMapper.insert(order);
//    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public Orders findOrdersById(String id) {
        //查询order
        Order order = orderMapper.selectByPrimaryKey(id);
        //查询OrderIter列表
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",id);
        List<OrderItem> orders = orderItemMapper.selectByExample(example);
        Orders orders1 = new Orders();
        orders1.setOrder(order);
        orders1.setOrderItem(orders);
        return orders1;
    }

    @Override
    @Transactional
    public void batchSend(List<Order> orders) {
        for (Order order : orders) {
            if(order.getShippingCode()==null || order.getShippingName()==null){
                throw new RuntimeException("请选择快递公司和填写快递单号请选择快递公司和填写快递单号");
            }
        }
        for (Order order : orders) {
            order.setOrderStatus("3");
            order.setConsignStatus("2");
            order.setConsignTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }
    }

    public void orderTimeOutLogic() {
        //订单超时未付款   自动关闭
        //查询订单设置表的超时时间
        OrderConfig order = orderConfigMapper.selectByPrimaryKey(1);

        Integer orderTimeout = order.getOrderTimeout();//超时时间

        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);

        //查询订单表   设置查询条件
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        //criteria.andLessThan("createTime",localDateTime);//创建时间小于超时时间
        criteria.andEqualTo("orderStatus","0");//条件是未付款的状态
        criteria.andEqualTo("isDelete","0");//未删除的订单

        List<Order> orders = orderMapper.selectByExample(example);

        for (Order order1 : orders) {
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("system");//操作人员
            orderLog.setOperateTime(new Date());//操作时间
            orderLog.setPayStatus(order1.getPayStatus());
            orderLog.setConsignStatus(order1.getConsignStatus());
            orderLog.setOrderId(order1.getId());
            orderLogMapper.insert(orderLog);

            order1.setOrderStatus("4");
            order1.setCloseTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order1);
        }
        //更新超市订单的状态
    }


    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            if(searchMap.get("ids")!=null ){
                //String ids = JSON.toJSONString(searchMap.get("ids"));
                //criteria.andIn("id",JSON.parseArray(ids));
                criteria.andIn("id",Arrays.asList((String[])searchMap.get("ids")));
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 精确查询
            if(searchMap.get("userName")!=null && !"".equals(searchMap.get("userName"))){
                criteria.andEqualTo("username",searchMap.get("userName"));
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andEqualTo("buyerRate",searchMap.get("buyerRate"));
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
